<?php
require_once 'phpmoko/lib/common.php';

class SQLite
{
	/**
	 *
	 * @var SQLite3
	 */
	private $sqlite = null;
	private $showSQL = false;
	private $file;

	/**
	 * Si file es null es una base de datos en memoria
	 *
	 * @param string $file
	 */
	function __construct($file = null)
	{
		$this->file = $file;
	}

	function __destruct()
	{
		if ($this->sqlite != null)
			$this->sqlite->close();
	}

	/**
	 *
	 * @return SQLite3
	 */
	function getSQLite()
	{
		if ($this->sqlite == null) {
			$this->sqlite = new SQLite3(($this->file != null) ? $this->file : ':memory:');
			$this->sqlite->busyTimeout(2000);
			$this->sqlite->exec("pragma synchronous = off;");
		}
		return $this->sqlite;
	}

	function showSQL($showSQL)
	{
		$this->showSQL = $showSQL;
	}

	/**
	 *
	 * @param SQLiteCommand $command
	 */
	function exec($command)
	{
		$query = $command->generateSQL();
		$sqlite = $this->getSQLite();

		$sqlite->exec($query);

		if ($this->showSQL) {
			require_once 'phpmoko/utils/Console.php';
			Console::debug($query);
		}
	}

	/**
	 *
	 * @param SQLiteCommand $command
	 * @return SQLiteDataResult
	 */
	function query($command)
	{
		$sqlite = $this->getSQLite();

		$query = $command->generateSQL();

		$result = $sqlite->query($query);

		if ($this->showSQL) {
			require_once 'phpmoko/utils/Console.php';
			Console::debug($query);
		}

		require_once 'phpmoko/db/SQLiteDataResult.php';

		return new SQLiteDataResult($sqlite, $result);
	}

	function tableExist($table)
	{
		$command = new SQLiteCommand("SELECT name FROM sqlite_master WHERE type='table' AND name={table};");
		$command->setVariable('table', $table);
		$result = $this->query($command);
		if ($result->fetchAssoc())
			return true;
		return false;
	}

	function insertId()
	{
		return $this->getSQLite()->lastInsertRowID();
	}
}
?>